import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { toast } from 'react-toastify';
import { FaCheckCircle, FaTrashAlt, FaClock } from 'react-icons/fa';
import './Notifications.css';

const NotificationList = ({ onMarkAsRead }) => {
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [page, setPage] = useState(1);
  const [pagination, setPagination] = useState({
    total: 0,
    pages: 0,
    limit: 10
  });
  const [filter, setFilter] = useState('all'); // 'all', 'unread', 'read'
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser);
  // 获取任务列表
  useEffect(() => {
    fetchNotifications();
  }, [page, filter]);

  const fetchNotifications = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      params.append('page', page);
      params.append('limit', pagination.limit);
      if (filter !== 'all') {
        params.append('isRead', filter === 'read');
      }

      const res = await axios.get(`/notifications?${params.toString()}`);
      setNotifications(res.data.notifications || []);
      setPagination(res.data.pagination || {
        total: 0,
        pages: 0,
        limit: 10
      });
    } catch (err) {
      console.error('获取任务列表失败', err);
      setError('获取任务失败，请刷新页面重试');
    } finally {
      setLoading(false);
    }
  };

  // 标记任务为已读
  const handleMarkAsRead = async (notificationId) => {
    try {
      await axios.patch(`/notifications/${notificationId}/read`);
      setNotifications(prevNotifications =>
        prevNotifications.map(notification =>
          notification.id === notificationId
            ? { ...notification, is_read: true }
            : notification
        )
      );
      toast.success('任务已标记为已读');
      if (typeof onMarkAsRead === 'function') {
        onMarkAsRead(notificationId);
      }
    } catch (err) {
      console.error('标记任务为已读失败', err);
      toast.error('操作失败，请稍后重试');
    }
  };

  // 删除任务
  const handleDeleteNotification = async (notificationId) => {
    if (!window.confirm('确定要删除这条任务吗？')) {
      return;
    }

    try {
      await axios.delete(`/notifications/${notificationId}`);
      setNotifications(prevNotifications =>
        prevNotifications.filter(notification => notification.id !== notificationId)
      );
      toast.success('任务已删除');
    } catch (err) {
      console.error('删除任务失败', err);
      toast.error('删除失败，请稍后重试');
    }
  };

  // 切换筛选条件
  const handleFilterChange = (newFilter) => {
    setFilter(newFilter);
    setPage(1); // 重置到第一页
  };

  // 分页处理
  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= pagination.pages) {
      setPage(newPage);
      window.scrollTo(0, 0);
    }
  };

  if (loading) {
    return <div className="loading">加载任务中...</div>;
  }

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  return (
    <div className="notifications-container">
      <div className="notifications-header">
        <h1 className="page-title">任务管理</h1>

        <div className="notifications-filter">
          <button
            className={`btn ${filter === 'all' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => handleFilterChange('all')}
          >
            全部任务
          </button>
          <button
            className={`btn ${filter === 'unread' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => handleFilterChange('unread')}
          >
            未读任务
          </button>
          <button
            className={`btn ${filter === 'read' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => handleFilterChange('read')}
          >
            已查收任务
          </button>
        </div>
      </div>

      {notifications.length === 0 ? (
        <div className="no-notifications">
          <p>暂无通知</p>
        </div>
      ) : (
        <div className="notifications-list">
          {notifications.map(notification => (
            <div
              key={notification.id}
              className={`notification-item ${!notification.is_read ? 'unread' : ''}`}
            >
              <div className="notification-header">
                <h3 className="notification-title">
                  {notification.title}
                  {notification.recurrence_type && (
                    <span className="scheduled-indicator" title="定时任务">
                      <FaClock />
                    </span>
                  )}
                </h3>
                <div className="notification-actions">
                  {!notification.is_read && (
                    <button
                      className="btn-icon btn-mark-read"
                      onClick={() => handleMarkAsRead(notification.id)}
                      title="标记为已读"
                    >
                      <FaCheckCircle />
                    </button>
                  )}
                  {(notification.sender_id === currentUser.id || currentUser.role === "admin") && (
            <button
              className="btn-icon btn-delete"
              onClick={() => handleDeleteNotification(notification.id)}
              title="删除"
            >
              <FaTrashAlt />
            </button>
          )}
                </div>
              </div>

              <div className="notification-meta">
                <span className="notification-sender">
                  发送者: {notification.sender_full_name || notification.sender_username}
                </span>
                <span className="notification-recipient">
                  接收者: {notification.recipient_full_name || notification.recipient_username}
                </span>
                <span className="notification-time">
                  {new Date(notification.created_at).toLocaleString()}
                </span>
              </div>

              <div className="notification-content">
                {notification.content}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 分页控件 */}
      {pagination.pages > 1 && (
        <div className="pagination">
          <button
            className="btn btn-secondary"
            onClick={() => handlePageChange(page - 1)}
            disabled={page === 1}
          >
            上一页
          </button>

          <div className="page-numbers">
            {Array.from({ length: pagination.pages }, (_, i) => i + 1).map(num => (
              <button
                key={num}
                className={`btn ${page === num ? 'btn-primary' : 'btn-outline'}`}
                onClick={() => handlePageChange(num)}
              >
                {num}
              </button>
            ))}
          </div>

          <button
            className="btn btn-secondary"
            onClick={() => handlePageChange(page + 1)}
            disabled={page === pagination.pages}
          >
            下一页
          </button>
        </div>
      )}
    </div>
  );
};

export default NotificationList;